# 操作csv
import csv

headers = ['no', 'name', 'sex', 'height', 'age']
rows = [
    ['A1001', 'xiaozhao', 'male', 168, 23],
    ['A1002', 'xiaoqian', 'female', 162, 22],
    ['A1003', 'xiaosun', 'female', 163, 21],
    ['A1004', 'xiaoli', 'male', 158, 21]
]
# 单行/多行列表写入
with open('test.csv', 'w', newline='') as f:  # 以写的方式打开文件 ,newline如果打开csv文件出现空行，可加上此参数
    writer = csv.writer(f)  # 实例化写对象
    writer.writerow(headers)  # 写入标题行(单行写入)
    writer.writerows(rows)  # 写入列表数据(多行写入)

# 字典式写入
headers = ['no', 'name', 'sex', 'height', 'age']
rows = [
    {'no': 'A1001', 'name': 'xiaozhao', 'sex': 'male', 'height': 168, 'age': 23},
    {'no': 'A1002', 'name': 'xiaoqian', 'sex': 'female', 'height': 162, 'age': 22},
    {'no': 'A1003', 'name': 'xiaosun', 'sex': 'female', 'height': 163, 'age': 21},
    {'no': 'A1004', 'name': 'xiaoli', 'sex': 'male', 'height': 158, 'age': 21}
]
with open('test.csv', 'a+', newline='') as f:
    f_csv = csv.DictWriter(f, headers)
    f_csv.writeheader()
    f_csv.writerows(rows)

# 列表式读取
with open('test.csv')as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# 字典式读取
with open('test.csv')as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)
        print(row['no'])
